﻿using Growatt.OutPutDataProcess;
using Growatt.WaveData.DataSetResolve;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Vosc;
using Vosc.VirtualOscilloscope;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Growatt.WaveData.VirtualOscilloscope
{
    public partial class FrmFindAddress : Form
    {

        private UIComboDataGridView comboBox_Selecet = new UIComboDataGridView()
        {
            DropDownWidth = 500,
            ForeColor = Color.Blue,
           DropDownStyle = UIDropDownStyle.DropDown,
            Font = new System.Drawing.Font("宋体", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)))
        };

        private List<ItemConfig> _configs = new List<ItemConfig>();
        private string _dataFilePath = "configData.json";
        private readonly ModelSaveString cuurentSelectItem;
        private readonly Action<ItemConfig> callBack;
        UIDataGridView uIDataGridView = null;

        public FrmFindAddress(ModelSaveString cuurentSelectItem, Action<ItemConfig> CallBack)
        {
            InitializeComponent();
            LoadConfigs();
            panel1.Controls.Add(comboBox_Selecet);
            comboBox2.Items.AddRange(Enum.GetNames(typeof(ENUM_001)).ToArray());
            comboBox3.Items.AddRange(Enum.GetNames(typeof(ENUM_Ratio)).ToArray());
            this.cuurentSelectItem = cuurentSelectItem;
            callBack = CallBack;
            if (cuurentSelectItem != null)
            {
                textBox1.Text = cuurentSelectItem.Address;
                comboBox2.Text = cuurentSelectItem.Type;
                comboBox3.Text = cuurentSelectItem.Scale;
                comboBox1.Text = cuurentSelectItem.Name;
                comboBox_Selecet.Text = cuurentSelectItem.Name;
            }
            this.FormClosed += Form2_FormClosed;
            comboBox_Selecet.DataGridView.Init();
            comboBox_Selecet.DataGridView.MultiSelect = true;//设置可多选
            comboBox_Selecet.ItemSize = new System.Drawing.Size(500, 200);
            comboBox_Selecet.DataGridView.AddColumn("参数名称", "ComboBoxItem");
            comboBox_Selecet.DataGridView.AddColumn("类型", "TypeContent", fillWeight: 20);
            comboBox_Selecet.DataGridView.AddColumn("倍率", "ScaleContent", fillWeight: 20);
            comboBox_Selecet.DataGridView.AddColumn("地址", "AddressContent", fillWeight: 40);
            comboBox_Selecet.DataGridView.AddCheckBoxColumn("删除", "Iselected", fillWeight: 30, readOnly: false);
            comboBox_Selecet.DataGridView.ReadOnly = false;
            comboBox_Selecet.ShowFilter = true;
            //点击删除按钮
            comboBox_Selecet.item.DelItems += () =>
            {
                var del = _configs.FindAll(o => o.Iselected);
                for (global::System.Int32 j = 0; j < del.Count; j++)
                {
                    var delModel = del[j];
                    if (delModel != null)
                        _configs.Remove(delModel);
                }
                SaveConfigs();
                LoadConfigs();
               label_status.Text=("删除成功!");
            };
            comboBox_Selecet.ShowText = true;
            comboBox_Selecet.BackColor = Color.Red;
            comboBox_Selecet.ForeColor = Color.Gray;
            var font = new System.Drawing.Font("微软雅黑", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            comboBox_Selecet.Font = font;

            itemConfigs = new BindingList<ItemConfig>(_configs) { };
            comboBox_Selecet.DataGridView.DataSource = itemConfigs;
            comboBox_Selecet.ValueChanged += new Sunny.UI.UIComboDataGridView.OnValueChanged(this.uiComboDataGridView2_ValueChanged);
            comboBox1.SelectedIndexChanged += (s, e) =>
            {
                try
                {
                    int index = comboBox1.SelectedIndex;
                    if (index != -1)
                    {
                        textBox1.Text = _configs[index].AddressContent;
                        comboBox2.Text = _configs[index].TypeContent;
                        comboBox3.Text = _configs[index].ScaleContent;

                    }
                }
                catch (Exception ex)
                {


                }
            };
            panel1.Width = 326;
            comboBox_Selecet.Dock = DockStyle.Top;
            this.StartPosition = FormStartPosition.CenterScreen;
            comboBox_Selecet.ForeColor = Color.Black;
            comboBox_Selecet.Font = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
        }
        BindingList<ItemConfig> itemConfigs = new BindingList<ItemConfig>();
        private void uiComboDataGridView2_ValueChanged(object sender, object value)
        {
            if (value != null && value is DataGridViewSelectedRowCollection)
            {
                DataGridViewSelectedRowCollection collection = (DataGridViewSelectedRowCollection)value;
                foreach (var item in collection)
                {
                    DataGridViewRow row = (DataGridViewRow)item;
                    ItemConfig selectParaInfo = row.DataBoundItem as ItemConfig;
                    textBox1.Text = selectParaInfo.AddressContent;
                    comboBox2.Text = selectParaInfo.TypeContent;
                    comboBox3.Text = selectParaInfo.ScaleContent;
                    itemConfigCurrent = selectParaInfo;
                    comboBox_Selecet.Text = selectParaInfo.ComboBoxItem;
                }
            }
        }

        ItemConfig itemConfigCurrent = null;

        private void Form2_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (itemConfigCurrent != null)
            {
                callBack.Invoke(itemConfigCurrent);
            }
        }

        private void LoadConfigs()
        {
            if (File.Exists(_dataFilePath))
            {
                string jsonData = File.ReadAllText(_dataFilePath);
                _configs = JsonConvert.DeserializeObject<List<ItemConfig>>(jsonData);
                PopulateComboBox();
                itemConfigs.Clear();
                foreach (var item in _configs)
                {
                    itemConfigs.Add( item);
                }
                itemConfigs.ResetBindings();
            }
        }
        private void PopulateComboBox()
        {
            comboBox1.Items.Clear();
            foreach (var config in _configs)
            {
                comboBox1.Items.Add(config.ComboBoxItem);
            }
        }

        private void SaveConfigs()
        {
            string jsonData = JsonConvert.SerializeObject(_configs, Formatting.Indented);
            File.WriteAllText(_dataFilePath, jsonData);
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            label_status.Text = string.Empty;
            textBox1.Text = string.Empty;
            VariableInfo variableInfo = new VariableInfo(comboBox_Selecet.Text, string.Empty);
            DwarfHelper.DwarfHelperInstance.GetAddress(new List<VariableInfo>() { variableInfo });
            if (!string.IsNullOrEmpty(variableInfo.Address))
            {
                textBox1.Text = variableInfo.Address;
            }
            else
            {
               label_status.Text=("查询失败");
            }
            if (!string.IsNullOrEmpty(comboBox_Selecet.Text))
            {
                var datalist = _configs.FirstOrDefault(o => o.ComboBoxItem.Equals(comboBox_Selecet.Text) && o.AddressContent.Equals(textBox1.Text)
                  && o.TypeContent.Equals(comboBox2.Text)
                  && o.ScaleContent.Equals(comboBox3.Text)
                  );
                if (datalist == null)
                {
                    var data = new ItemConfig { ComboBoxItem = comboBox_Selecet.Text, AddressContent = textBox1.Text, TypeContent = comboBox2.Text, ScaleContent = comboBox3.Text };
                    _configs.Insert(0,data);
                    comboBox1.Items.Add(comboBox1.Text);
                    SaveConfigs();
                    LoadConfigs();
                    itemConfigCurrent = data;
                   label_status.Text=("添加成功!");
                }
                itemConfigs.ResetBindings();
            }
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            var datalist = _configs.FirstOrDefault(o => o.ComboBoxItem.Equals(comboBox_Selecet.Text) && o.AddressContent.Equals(textBox1.Text)
                     && o.TypeContent.Equals(comboBox2.Text)
                     && o.ScaleContent.Equals(comboBox3.Text)
                     );
            if (datalist != null)
            {
                _configs.Remove(datalist);
                SaveConfigs();
                LoadConfigs();
                comboBox_Selecet.Text = string.Empty;
               label_status.Text=("删除成功!");
            }
        }



        private void button3_Click(object sender, EventArgs e)
        {
            if (File.Exists(_dataFilePath))
            {
                File.Delete(_dataFilePath);
            }
            LoadConfigs();
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }
    }
}
